import 'dart:async';

import 'package:gold/app/order_event.dart';
import 'package:gold/base/config.dart';
import 'package:gold/base/list_view_model.dart';
import 'package:gold/model/order_model.dart';
import 'package:gold/route/routes.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/utils/xfg_extension.dart';

/// @description:
/// @author tangzhentao
/// @created at 21:34 2024/12/14

class ShopOrderListViewmodel extends ListViewModel<OrderModel> {
  /// 订单状态 空字符串=全部 0=待支付,1=待发货,2=待收货（待提货,4=已完成
  final String _orderStatus;

  /// 去发货订单监听
  StreamSubscription<ShipOrder>? _shipSubscription;

  ShopOrderListViewmodel(super.api, this._orderStatus) {
    /// 去发货订单
    if (_orderStatus == OrderStatus.all || _orderStatus == OrderStatus.receiving) {
      _shipSubscription = XfgNav.eventBus.on<ShipOrder>().listen((result) {
        if (_orderStatus == OrderStatus.receiving) {
          refresh();
        } else {
          final id = result.orderId;
          /// 下标
          int index = -1;
          for (var order in list) {
            if (order.id == id) {
              index = list.indexOf(order);
            }
          }
          if (index >= 0) {
            list[index].status = OrderStatus.receiving;
            setSuccessChange();
          }
        }
      });
    }
  }

  /// 收货显示改变
  void changeAddressShow(int index) {
    list[index].showAddress = !(list[index].showAddress?? false);
    setSuccessChange();
  }

  /// 自行寄快递
  Future expressDelivery(int index) async {
    if (!_isValidOrder(index)) return;
    final result = await XfgNav.pushNamed(Routes.settingsSetExpress, arguments: {'orderId': list[index].id!, 'isShopOrder': true});
    if (result == true) {
      if (_orderStatus == OrderStatus.sending) {
        /// 当前待发货页面
        _removeAt(index);
      } else {
        XfgNav.eventBus.fire(ShipOrder(list[index].id!));
      }
    }
  }

  /// 查看物流
  Future checkLogistics(int index) async {
    final order = list[index];
    final expressDetail = order.express?.expressDetail;
    if (expressDetail != null && expressDetail.status != null && expressDetail.status != 1 && order.address != null && order.detail?.product != null) {
      XfgNav.pushNamed(Routes.myOrderLogistics, arguments: {
        'product': order.detail?.product!, 'address': order.address!, 'express': expressDetail});
    } else {
      '物流/商品/地址信息异常'.info();
    }
  }

  /// 移除传入下标数据并刷新
  void _removeAt(int index) {
    list.removeAt(index);
    if (list.isNotEmpty) {
      setSuccessChange();
    } else {
      setEmpty();
    }
  }

  /// 有效订单
  bool _isValidOrder(int index) {
    final id = list[index].id;
    final result = id != null;
    if (!result) {
      '订单信息异常'.error();
    }
    return result;
  }

  @override
  Map<String, dynamic>? onOtherData() {
    return {'status': _orderStatus};
  }

  @override
  void dispose() {
    _shipSubscription?.cancel();
    _shipSubscription = null;
    super.dispose();
  }
}
